package br.mia.unifor.onaga.cloud.execute.factory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import br.mia.unifor.onaga.cloud.artifact.Provider;
import br.mia.unifor.onaga.cloud.execute.ComputeProvider;
import br.mia.unifor.onaga.cloud.execute.EC2ComputeProvider;
import br.mia.unifor.onaga.cloud.execute.Main;
import br.mia.unifor.onaga.cloud.execute.RackspaceComputeProvider;

public class ComputeProviderFactory {
	public static final Map<String, ComputeProvider> map = new Hashtable<String, ComputeProvider>();
	static Logger log = Logger.getLogger(ComputeProviderFactory.class.getName());

	public static ComputeProvider getProvider(Provider provider)
			throws IOException {
		ComputeProvider lComputeProvider = map.get(provider.getName());

		if (lComputeProvider == null) {
			
			Properties properties = new Properties();
			
			InputStream input = Main.class.getClass()
					.getResourceAsStream(provider.getCredentialPath());
			if(input == null){			
				input = new FileInputStream(provider.getCredentialPath());
			}
			
			properties.load(input);
			
			log.info("Carregando o provedor "+provider.getName());
			
			provider.setUserName(properties.getProperty("userName"));
			provider.setPrivateKey(properties.getProperty("privateKey"));
			provider.setPassword(properties.getProperty("password"));
			provider.setName(properties.getProperty("name"));
			
			

			if ("aws-ec2".equals(provider.getName())) {

				lComputeProvider = new EC2ComputeProvider(provider);
			} else if ("cloudservers-us".equals(provider.getName())) {
				lComputeProvider = new RackspaceComputeProvider(provider);

			} else if ("dummy".equals(provider)) {
				// do nothing

			}
			
			log.info("o provedor "+provider.getName()+" foi carregado com sucesso");

			map.put(provider.getName(), lComputeProvider);
		}

		return lComputeProvider;
	}
}
